// pages/discover/traerDetail/index.js
import axios, {
  baseUrl
} from '../../../utils/axios';
import dayjs from 'dayjs';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatraList: [],
    desc: "",
    price: 0,
    startTime: new Date().getTime(),
    endTime: new Date().getTime(),
    confirmBtn: {
      content: '知道了',
      variant: 'base'
    },
    phone: "",
    dpName: "",
    nickName:"",
    preTip: false,
    visible: {open:false}
  },
  onInput(e) {
    const {
      u
    } = e?.currentTarget?.dataset;
    this.setData({
      [u]: e.detail.value
    })
  },
  showPicker(e) {
    const {
      mode
    } = e?.currentTarget?.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail;
    const {
      mode
    } = this.data;
    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
    });

    this.hidePicker();
  },

  onColumnChange(e) {
    console.log('pick', e?.detail?.value);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options?.id) {
      this.userId = options.id * 1;
      this.getDetail(this.userId);
      this.openid = wx.getStorageSync('openid');
    } else {
      wx.navigateBack()
    }
  },
  closeDialog() {
    this.setData({
      modal: {
        ...this.data.modal,
        open:false
      }
    })
    if (!this.data.preTip) {
      wx.navigateTo({
        url: '/pages/usercenter/teaerRecord/record',
      })
    } else {
      this.setData({
        preTip: false
      })
      this.yuyuecys();
    }

  },
  yuyuePre() {
    this.setData({
      preTip: true,
      modal: {
        open:true,
        title: "注意",
        content: "预约非本茶室的订单，茶艺师有权无理由拒单！"
      }
    })
  },
  yuyuecys() {
    const {
      startTimeText,
      duration,
      dpName,
      phone,
      nickName,
      remark = ""
    } = this.data;
    if (!dpName) {
      wx.showToast({
        title: '请输入店铺名称！',
      })
      return;
    }
    if (!phone) {
      wx.showToast({
        title: '请输入您的联系方式！',
      })
      return;
    }

    if (startTimeText && duration) {
      const date1 = dayjs(startTimeText);
      const endTimeText = date1.add(duration,"hour").format("YYYY-MM-DD HH:mm:ss")
      let payment = duration*this.data.price;
      axios.post("/app/createOrder", {
        source: "小程序",
        startTime: startTimeText,
        endTime: endTimeText,
        payment,
        userId: this.userId,
        status: 1,
        remark: JSON.stringify({
          "remark": remark,
          "phone": phone,
          "dpName": dpName,
          "nickName":nickName
        }),
        type: 4,
        wxId: this.openid
      }).then(res => {
        this.wxPay({
          price: payment,
          balance: 0,
          orderId: res.orderId,
        })
      })
    } else {
      wx.showToast({
        title: '请选择预约时间及时长',
        icon: "none"
      })
    }
  },
  payCallback() {
    this.setData({
      modal: {
        open:true,
        title: "预约成功",
        content: "稍后茶艺师会主动联系您！"
      }
    })
  },
  wxPay(amounts) {
    axios.post('/app/toPay', {
        openid: this.openid,
        orderId: amounts.orderId,
        name: `预约茶艺师(${this.data.teaerName})`,
        payment: amounts.price,
        balance: amounts.balance
      })
      .then((res) => {
        if (res.data === "success") {
          this.payCallback()
          return;
        }
        const that = this;
        if(res.data === null){
          wx.showToast({
            title: '支付失败！',
            icon:"none"
          })
        }
        const {
          nonceStr,
          timeStamp,
          signType,
          paySign
        } = res.data;
        wx.requestPayment({
          timeStamp,
          nonceStr,
          package: res.data.package,
          signType,
          paySign,
          success() {
            that.payCallback()
          },
          fail() {
            wx.showToast({
              title: '支付取消',
              icon: 'error'
            })
          },
        });
      });
  },
  async getDetail(id) {
    await axios.get("/app/queryTeaerList", {
      id
    }).then(res => {
      const data = res.data[0]
      this.setData({
        avatraList: data.avatar.map(item => baseUrl + item.url),
        desc: data.desc,
        price: data.price,
        teaerName: data.name
      })
      console.log(this.data.avatraList)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})